package com.example.lyonlinemusic.controller;

import com.example.lyonlinemusic.mapper.MusicMapper;
import com.example.lyonlinemusic.model.Music;
import com.example.lyonlinemusic.model.User;
import com.example.lyonlinemusic.tools.Constant;
import com.example.lyonlinemusic.tools.ResponseBodyMessage;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.ClientInfoStatus;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MusicController {

    //读取配置文件的内容
    @Value("${music.local.path}")
    private String SAVE_PATH;

    @Autowired
    private MusicMapper musicMapper;



    //上传音乐
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer, @RequestParam("filename")MultipartFile file, HttpServletRequest request){
        //检查是否登录
        HttpSession httpSession=request.getSession(false);
        if(httpSession==null||httpSession.getAttribute(Constant.USERINFO_SESSION_KEY)==null){
            System.out.println("没有登录！");
            return new ResponseBodyMessage<>(-1,"请登录后上传",false);
        }


        //查询数据库中是否存在当前音乐（歌曲名和歌手是否相同）
        String fileNameAndType=file.getOriginalFilename();//获取文件的名字，×××.mps3
        //System.out.println("fileNameAndType:"+fileNameAndType);
        int index=fileNameAndType.lastIndexOf(".");
        String title=fileNameAndType.substring(0,index);

        Music music=musicMapper.selectByTitleAndSinger(title,singer);
        if(music!=null){
            return new ResponseBodyMessage<>(-1,"服务器上传失败,不能上传重复歌曲!",false);
        }


        //上传到服务器
        String path=SAVE_PATH+fileNameAndType;
        File dest=new File(path);
        if(!dest.exists()){
            dest.mkdir();
        }
        try {
            file.transferTo(dest);//把file存到dest路径中
            //return new ResponseBodyMessage<>(0,"上传成功!",true);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"服务器上传失败!",false);
        }


        //进行数据库的上传
        User user= (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid=user.getId();

        String url="/music/get?path="+title;//播放音乐路径

        SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd");
        String time=sf.format(new Date());

        try{
            int ret=0;
            ret=musicMapper.insert(title,singer,time,url,userid);
            if(ret==1){
                return new ResponseBodyMessage<>(0,"数据库上传成功!",true);
            }else{
                return new ResponseBodyMessage<>(-1,"数据库上传失败!",false);
            }
        }catch(BindingException e){
            dest.delete();//如果服务器上传成功，但是数据库没有上传唱歌，此时删掉服务器的内容
            return new ResponseBodyMessage<>(-1,"数据库上传失败!",false);
        }

    }




    //播放音乐
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path){//读取指定路径下音乐的信息，并把文件以字节的形式返回给前端
        File file=new File(SAVE_PATH+path);
        try {
            byte[] a= Files.readAllBytes(file.toPath());//读取文件中的所有的字节
            if(a==null){
                return ResponseEntity.badRequest().build();//返回400
            }
            return ResponseEntity.ok(a);//能够返回a的信息，及ok状态
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }



    //删除单首音乐
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicBuId(@RequestParam int id){
        //检查当前id的音乐是否存在
        Music music=musicMapper.findMusicById(id);
        if(music==null){
            System.out.println("没有这个id的音乐");
            return new ResponseBodyMessage<>(-1,"没有那你要删除的音乐！",false);
        }else{
            //删除数据库上的音乐数据
            int ret=musicMapper.deleteMusicById(id);
            if(ret==1){
                //删除服务器上的音乐数据
                String fileName=music.getTitle();
                File file=new File(SAVE_PATH+fileName+".mp3");
                System.out.println(file.toPath());
                boolean result=file.delete();
                if(result){
                    return new ResponseBodyMessage<>(0,"数据库和服务器中的音乐都删除成功！",true);
                }else{
                    return new ResponseBodyMessage<>(-1,"服务器中的音乐删除失败！",false);
                }
            }else{
                return new ResponseBodyMessage<>(-1,"数据库中的音乐删除失败！",false);
            }
        }
    }



    //删除多首音乐
    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id){
        System.out.println("所有的ID:"+id);
        int sum=0;
        for (int i = 0; i < id.size(); i++) {
            //检查当前id的音乐是否存在
            Music music = musicMapper.findMusicById(id.get(i));
            if (music == null) {
                System.out.println("没有这个id的音乐");
                return new ResponseBodyMessage<>(-1, "没有那你要删除的音乐！", false);
            } else {
                //删除数据库上的音乐数据
                int ret = musicMapper.deleteMusicById(id.get(i));
                if (ret == 1) {
                    //删除服务器上的音乐数据
                    String fileName = music.getTitle();
                    File file = new File(SAVE_PATH + fileName + ".mp3");
                    boolean result=file.delete();
                    if(result){
                        sum+=ret;
                    }else{
                        return new ResponseBodyMessage<>(-1,"服务器中的音乐删除失败！",false);
                    }
                }else{
                    return new ResponseBodyMessage<>(-1,"数据库中的音乐删除失败！",false);
                }
            }
        }
        if(sum==id.size()){
            System.out.println("整体删除成功！");
            return new ResponseBodyMessage<>(0,"音乐删除成功！",true);
        }else{
            System.out.println("整体删除失败！");
            return new ResponseBodyMessage<>(-1,"音乐删除失败！",false);
        }
    }



    //查询音乐
    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        List<Music> musicList=null;
        if(musicName!=null){
            musicList=musicMapper.findMusicByName(musicName);
        }else{
            musicList=musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(0,"查询到了所有的音乐",musicList);
    }



}
